<?php
/**
 * @author Thibaut Cromphaut, Gaïtano Boeraeve, Mathias Helin, Dimitry Dierickx
 * @copyright  Copyright (c) 2011 Artevelde University College Ghent 
 */

class ArticleController extends Zend_Controller_Action
{
    public function init()
    {
        $this->stylesBase = $this->view->baseUrl() . '/styles/';
    }
    
    /**
     * This will validate our session and the requestion action;
     */
    public function preDispatch()
    {
        // Check our identity
        if(Zend_Auth::getInstance()->hasIdentity())
        {
            // Check the requestion action
            switch ( $this->getRequest()->getActionName())
            {
                case 'index':
                case 'search':
                case 'add':
                case 'edit':
                case 'delete':
                case 'view':
                    // -- These actions are allowed, nothing to do -- //
                    break;
                default:
                    // -- Invalid action requested, refer to homepage -- //
                    $this->_helper->redirector('index', 'index');
                    break;
            }
        }
        else
        {
            // -- No session, refer to loginpage -- //
            $this->_helper->redirector('login', 'user');
        }
    }

    /**
     * This is the main action.
     * Displays all the articles
     */
    public function indexAction()
    {
        // Load variables
        $articles   = null;
        
        // Prepare the view
        $view   = $this->_getView('Articles');
        
        // AJAX Search form
        $search = $this->_getArticleSearchForm();        
        $search->getElement('searchstring')->setJQueryParam('source', $view->baseUrl('article/search'));
        
        // What to display?
        $request = $this->getRequest();        
        if($request->isPost())
        {
            if($search->isValid($request->getPost()))
            {
                $article_name   = $search->getValue('article_name');                                
                $articles       = $this->_getArticlesByName($article_name);
            }
        }
        
        // If there is no (valid) search, load all articles
        if($articles == null)
        {
            $articles = $this->_getAllArticles();
        }
        
        // Pass our variables to our view
        $view->headLink()->prependStylesheet('http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.16/themes/base/jquery-ui.css');
        $view->search   = $search;
        $view->articles = $articles;
    }
    
    /**
     * This will output a JSON array of Announcement Titles
     */
    public function searchAction()
    {
        // We only need a JSON result, no other output
        $this->_helper->layout()->disableLayout();
        $this->_helper->viewRenderer->setNoRender(true);
        
        // Load the results
        $articles = $this->_getArticlesByName($this->_getParam('term'));                
        $results  = array();    
        
        // We only need the name
        foreach($articles as $article)
        {            
            $results[] = $article->Name;
        }
        
        // Parse JSON
        $this->_helper->json($results);
    }
    
    public function addAction()
    {
        return $this->editAction();
    }
    
    /**
     * Displays the add/edit form
     */
    public function editAction()
    {
        // Set up basics
        $view = $this->_getView('Edit Article');
        $form = $this->_getEditArticleForm();
        
        // Are we submitting the form or not?        
        if($this->getRequest()->isPost()) 
	{
            // Get the form data an validate it
            $formData  = $this->_request->getPost();
            if ($form->isValid($formData)) 
            {
                // This will only be visible if something goes wrong
                $view = $this->_getView('Error - Edit Article');
                
                // Fetch our mapper
                $mapper = new Application_Model_ArticleMapper(); 
                
                // Prepare to save
                $values = $form->getValues();
                $article = new Application_Model_Article();
                $article->Id        = $values['article_id'];
                $article->Name      = $values['article_name'];
                $article->Text      = $values['article_text'];
                $article->ChapterId = $values['article_chapter_id'];
                
                // Save
                $mapper->save($article);
                
                // Redirect
                return $this->_helper->redirector('index', 'article');
            }
        }
        else
        {   
            // Check if we have an ID, if so, populate the form
            $id = (string)$this->getRequest()->getParam('id');            
            
            $article = $this->_getArticleById($id);                
            $form->populate(array(
                'article_id'            => $article->Id,    
                'article_name'          => $article->Name,
                'article_text'          => $article->Text,             
                'article_chapter_id'    => $article->ChapterId,
            ));
        }
        
        // Push our form
        $view->form = $form;
    }
    
    /**
     * Deletes an article
     */
    public function deleteAction()
    {
        // Get the ID and delete this announcement
        $id = (string)$this->getRequest()->getParam('id');
        $articleMapper = new Application_Model_ArticleMapper();
        $articleMapper->delete($id);
        $this->_helper->redirector('index', 'article');
    }
    
    /**
     * Returns an array of all active Articles
     *
     * @return Array(Application_Model_Article)
     */
    private function _getAllArticles()
    {
        $articleMapper = new Application_Model_ArticleMapper();
        return $articleMapper->fetchAll();
    }
    
    /**
     * Get the edit form
     *
     * @return Application_Form_EditArticle
     */
    private function _getEditArticleForm()
    {
        return new Application_Form_EditArticle(array(
            'action' => $this->view->baseUrl() . '/article/edit/',
            'post'   => 'post',
        ));
    }
    
    /**
     * Fetch an article by its ID
     *
     * @param integer $id
     * @return Application_Model_Article
     */
    private function _getArticleById($id)
    {
        $articleMapper = new Application_Model_ArticleMapper();
        return $articleMapper->fetchById($id);
    }

    /**
     * AJAX Search form, search article by name
     *
     * @return Application_Form_ArticleSearch
     */
    private function _getArticleSearchForm()
    {
        return new Application_Form_NameSearch(array(
            'action' => $this->view->baseUrl('article/index'),
            'method' => 'post',
        ));
    }
    
    /**
     * Get all articles by (part of) their name/title
     *
     * @return Array(Application_Model_Article)
     */
    private function _getArticlesByName($name)
    {
        $articleMapper = new Application_Model_ArticleMapper();
        return $articleMapper->fetchByName($name);
    }
    
    /**
     * This returns the view for this controller.
     * 
     * @param string $title
     * @return Zend_View
     */
    private function _getView($title)
    {
        $view = $this->view;
        $view->title = $title;
        $view->headTitle($view->title, 'PREPEND');

        return $view;
    }
}





